<?php
/*
 * @Author: lokei
 * @Date: 2022-11-16 09:03:59
 * @LastEditors: lokei
 * @LastEditTime: 2024-09-01 22:46:44
 * @Description: 
 */

namespace App\Http\Controllers\Rbac\Auth;

use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use App\Common\Alipay\Common;
use App\Models\Ucenter\FansModel;
use App\Models\Ucenter\UserModel;
use App\Services\Ucenter\FansService;
use App\Services\Ucenter\UserService;
use Illuminate\Support\Facades\Auth;

class AlipayController extends Controller
{
    private UserService $user_service;

    private FansService $fans_service;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
        $this->user_service = new UserService();
        $this->fans_service = new FansService();
    }

    public function login(Request $request)
    {

        Factory::setOptions(Common::getOptions());
        if (config('app.proj_identity') != null && config('app.proj_identity') != '') {
            $result = Factory::base()->oauth()->agent(config('app.app_auth_token'))->getToken($request->input('code'))->toMap();
        } else {
            $result = Factory::base()->oauth()->getToken($request->input('code'))->toMap();
        }

        $responseChecker = new ResponseChecker();
        if (true == $responseChecker->success($result)) {
            $open_id = '';
            if(array_key_exists('http_body', $result)) { // 新版本 open_id
                $http_body = json_decode($result['http_body'], true);
                if(array_key_exists('open_id', $http_body['alipay_system_oauth_token_response']) && $http_body['alipay_system_oauth_token_response']['open_id'] != null && $http_body['alipay_system_oauth_token_response']['open_id'] != '') {
                    $open_id = $http_body['alipay_system_oauth_token_response']['open_id'];
                }
            }
            if($open_id == '') { // 老版本 user_id
                if(array_key_exists('user_id', $result) && $result['user_id'] != null && $result['user_id'] != '') {
                    $open_id = $result['user_id'];
                }
            }
            
            if ($open_id != '') {
                $fans = FansModel::where('openid', '=', $open_id)->where('platform', '=', 'alipay')->first();
                if (!is_null($fans)) {
                    if (!($fans->uid > 0)) {
                        $uid = $this->user_service->createUser();
                        $fans->uid = $uid;
                        $fans->save();
                    } else {
                        $user = UserModel::where('uid', '=', $fans->uid)->first();
                        if (is_null($user)) {
                            $uid = $this->user_service->createUser();
                            $fans->uid = $uid;
                            $fans->save();
                        }
                    }
                } else {
                    $fid = $this->fans_service->registerOpenid('alipay', $open_id);
                    $fans = FansModel::where('openid', '=', $open_id)->first();
                    $uid = $this->user_service->createUser();
                    $fans->uid = $uid;
                    $fans->save();
                }
                if (!isset($user)) {
                    $user = UserModel::where('uid', '=', $fans->uid)->first();
                }
                $token = Auth::login($user);
                $res = ResultTool::success();
                $res['data']['token'] = $token;
                return $res;
            } else {
                app('log')->info('Alipay login failed without open_id', $result);
                $res = ResultTool::fail();
                $res['errorMsg'] = '小程序用户登入失败！';
                return $res;
            }
        } else {
            app('log')->info('Alipay login failed', $result);
            $res = ResultTool::fail();
            $res['errorMsg'] = '小程序用户登入失败！';
            return $res;
        }
    }
}
